// 设置进入各个页面的权限
var releaseExperimentCharacteristic = false;
var gotoExperimentalReportCharacteristic = false;
var gotoNodeManagementCharacteristic = false;
var gotoVideoManagementCharacteristic = false;
var userName = "";
var token = "";

/**
 * 获取用户信息
 * @returns {boolean}
 */

function getUserInfo() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/user/getUserInfoByToken",
        type: "POST",
        dataType:"json",
        contentType: "application/json;charset=UTF-8",
        headers: {
            token: token //这里是Token
        },
        cache: false,//设置不缓存
        success: getUserSuccess,
        error: showErrorInfo
    });
    return false;
}


/**
 * 获取用户信息成功之后的处理
 * @param data
 * @returns {boolean}
 */
function getUserSuccess(data) {

    // 判断是否登录
    if(!data.flag) {
        // 当前未登录，将跳转至登录页面
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        document.getElementById("userLogin").click();
    } else {
        // 当前已登录，得到用户信息
        var user = JSON.parse(data.msg);
        userName = user['name'];
        role = user['role'];

        // 判断当前登录的用户是否为教师
        if (role.indexOf("教师") === 0) {

            // 当前登录用户为教师
            teacherGetCoursesTop5();
        } else {

            // 当前登录用户为学生
            document.getElementById("userInfo").innerHTML = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='#'>Linux基础入门新版</a></li>" +
                "<li><a class=''  href='#'>高级bash编程指南</a></li>" +
                "<li><a class=''  href='#'>java实现记事本</a></li>" +
                "<li><a class='' href='#' >python实现文字聊天室</a></li>" +
                "<li><a class=''  href='#'>查看更多</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='#' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
        }

        if(releaseExperimentCharacteristic) {
            releaseExperimentCharacteristic = false;
            if(role.indexOf("教师") === 0) {
                window.location.href="/developer/index.html";
            } else {
                alert("抱歉，您的身份是：" + role + "  仅有教师可以发布实验！");
            }
        } else {
            if (gotoExperimentalReportCharacteristic) {
                gotoExperimentalReportCharacteristic = false;
                if (role.indexOf("教师") === 0) {
                    window.location.href = "/experimental_report/index.html";
                } else {
                    alert("抱歉，您的身份是：" + role + "  仅有教师可以查看实验报告！");
                }
            } else {
                if (gotoNodeManagementCharacteristic) {
                    gotoNodeManagementCharacteristic = false;
                    if (role.indexOf("教师") === 0) {
                        window.location.href = "/node_management/index.html";
                    } else {
                        alert("抱歉，您的身份是：" + role + "  仅有教师可以进行节点管理！");
                    }
                }else
                {
                    if (gotoVideoManagementCharacteristic){
                        gotoVideoManagementCharacteristic = false;
                        if(role.indexOf("教师") === 0) {
                            window.location.href = "/video/index.html";
                        } else {
                            alert("抱歉，您的身份是：" + role + "  仅有教师可以进行视频管理！");
                        }
                    }
                }
            }
        }
    }
    return false;
}


/**
 * 用于处理登录
 * @returns {boolean}
 */
function login() {
    var id = document.getElementById("id").value;
    var password = document.getElementById("password").value;
    var checkCode = document.getElementById("checkCode").value;
    if(id === "" || password === "" || checkCode === "") {
        // alert("所有字段不允许为空！");
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = "所有字段不可以为空！";
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
    const obj = {};
    obj.id = id;
    obj.password = password;
    obj.checkCode = checkCode;
    var token = getCookie("token");
    $.ajax({
        url: "/apis/user/login",
        type: "POST",
        cache: false,//设置不缓存
        dataType:"json",
        contentType: "application/json;charset=UTF-8",
        headers: {
            token: token //这里是Token
        },
        data: JSON.stringify(obj),
        success: loginSuccess,
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
        }
    });
    return false;
}

/**
 * ajax登录请求成功的回调函数
 * @param data
 * @returns {boolean}
 */
function loginSuccess(data) {
    if(data.flag) {
        setTokenToCookie(data.token);
        getUserInfo();
        document.getElementById("closeLogin").click();
    } else {
        // alert(data);
        document.getElementById("loginError").style.display = "block";
        document.getElementById("loginErrorMessage").innerHTML = data.msg;
        document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        setTimeout(clearLoginError, 1500);
        return false;
    }
}

function clearLoginError() {
    if(document.getElementById("loginError").style.display.indexOf("block") === 0) {
        document.getElementById("loginError").style.display = "none";
        document.getElementById("loginErrorMessage").innerHTML = "";
    }
}

/**
 * 退出登录处理
 */
function signOut() {
    deleteCookie("token");
    if ("no" === getCookie("token")){
        parent.location.reload();
    }else {
        alert("注销失败");
    }
}
/**
 * 进入发布实验页面前的处理
 */
function releaseExperiment() {
    gotoExperimentalReportCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    releaseExperimentCharacteristic = true;
    getUserInfo();
}

/**
 * ajax初始化获取用户信息请求成功后的回调函数
 * @param data
 * @returns {boolean}
 */
function getInitUserSuccess(data) {
    if(!data.flag) {
        alert("账号在其他地址或浏览器登录，请重新登录！");
        // 当前未登录，将跳转至登录页面
        // document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        // document.getElementById("userLogin").click();
    } else {
        var user = JSON.parse(data.msg);
        userName = user['name'];
        var role = user['role'];
        if (role.indexOf("教师") === 0) {
            teacherGetCoursesTop5();
        } else {
            var str = "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "我的课程" +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='#'>Linux基础入门新版</a></li>" +
                "<li><a class=''  href='#'>高级bash编程指南</a></li>" +
                "<li><a class=''  href='#'>java实现记事本</a></li>" +
                "<li><a class='' href='#' >python实现文字聊天室</a></li>" +
                "<li><a class=''  href='#'>查看更多</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>" +
                "<ul class='nav navbar-nav'>" +
                "<li class='dropdown'>" +
                "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
                "欢迎您，" + userName +
                "</a>" +
                "<ul class='dropdown-menu'>" +
                "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
                "<li><a class='' href='#' onclick='javascript:signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
                "</ul>" +
                "</li>" +
                "</ul>";
            document.getElementById("userInfo").innerHTML = str;
        }
        setTokenToCookie(data.token)
    }
    return false;
}

/**
 * 请求当前教师的前五个课程
 */
function teacherGetCoursesTop5() {
    var token = getCookie("token");
    $.ajax({
        url: "/apis/course/get_my_courses_top_number?topNumber=5",
        type: "GET",
        cache: false,//设置不缓存
        headers: {
            token: token //这里是Token
        },
        success: teacherGetCoursesTop5Success,
        error: showErrorInfo
    });
}

/**
 * 得到当前教师的前五个课程
 * @param data
 */
function teacherGetCoursesTop5Success(data) {
    var data = JSON.parse(data);
    var courseList = data['teacherCourses'];
    if(data.result=="error: 没有课程！") {
        //当前教师没有有课程
        var str = "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "我的课程" +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class=''>" + "没有课程" + "</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>" +
            "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "欢迎您，" + userName +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
            "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
            "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
            "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>";
        document.getElementById("userInfo").innerHTML = str;
    } else {
        // 当前老师有课程
        var str = "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "我的课程" +
            "</a>" +
            "<ul class='dropdown-menu'>";
        //var courses = JSON.parse(data)['teacherCourses'];
        for(var i = 0; i < courseList.length; i++) {
            var course = courseList[i];
            str += "<li><a class='' href='/developer/course_information.html?courseID=" + course.id + "'>" + course.name + "</a></li>";
        }
        if (courseList.length >= 5) {
            str += "<li><a class=''  href='/developer/index.html'>查看更多</a></li>" ;
        }
        str += "</ul>" +
            "</li>" +
            "</ul>" +
            "<ul class='nav navbar-nav'>" +
            "<li class='dropdown'>" +
            "<a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown'>" +
            "欢迎您，" + userName +
            "</a>" +
            "<ul class='dropdown-menu'>" +
            "<li><a class='' href='/home/index.html' >我的主页</a></li>" +
            "<li><a class='' href='/add_user/index.html' >添加用户</a></li>" +
            "<li><a class='' href='/back_stage/index.html' >后台管理</a></li>" +
            "<li><a class='' href='' onclick='signOut(); return false;' data-toggle='modal' data-target='#signOutModel'>退出登录</a></li>" +
            "</ul>" +
            "</li>" +
            "</ul>";
        document.getElementById("userInfo").innerHTML = str;
    }
}

function gotoExperimentalReport() {
    releaseExperimentCharacteristic = false;
    gotoNodeManagementCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    gotoExperimentalReportCharacteristic = true;
    getUserInfo();
}

function gotoNodeManagement() {
    releaseExperimentCharacteristic = false;
    gotoExperimentalReportCharacteristic = false;
    gotoVideoManagementCharacteristic = false;
    gotoNodeManagementCharacteristic = true;
    getUserInfo();
}

$(document).ready(function () {
    var token = getCookie("token");
    if (token === "no") {
        // document.getElementById("checkCodeImage").src = "/apis/checkcode/get_check_code?imageId=" + Math.random();
        // document.getElementById("userLogin").click();
    }else {
        $.ajax({
            url: "/apis/user/loginByToken",
            type: "POST",
            dataType:"json",
            contentType: "application/json;charset=UTF-8",
            headers: {
                token: token //这里是Token
            },
            cache: false,//设置不缓存
            success: getInitUserSuccess,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                showErrorInfo(XMLHttpRequest,textStatus,errorThrown);
            }
        });
    }
});
